﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CF_DAL_WS.Repositories
{
	#region using
	using CF_DAL_WS.Models;
	using CF_DAL_WS.Helpers;
    using System.Web.Security;
    using CF_DAL_WS.DTO;
    using System.IO;
    using System.Web.Hosting;
	#endregion
	public class UsersRepository
	{
		public List<Users> SelectAll()
		{
			try
			{
				return DataContext.Instance.Users.ToList();
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
			return new List<Users>();
		}

		public Users SelectByID(Guid id)
		{
			try
			{
				return DataContext.Instance.Users.FirstOrDefault(item => item.ID == id );
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
			return null;
		}

        public Users SelectByUserName(string username)
        {
            try
            {
                return DataContext.Instance.Users.FirstOrDefault(item => item.aspnet_Users.UserName == username);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error(ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error(ex.Message);
                }
            }
            return null;
        }

		public string Insert(string username, string password, string email, string role, string name, string phone, string address, ref string errorText)
		{
            errorText = string.Empty;
			try
			{
                MembershipCreateStatus createStatus;
                // Create new user
                MembershipUser newUser = Membership.CreateUser(username, password, email, "What is your favouritr color?", "Black Or White", true, out createStatus);

                switch (createStatus)
                {
                    case MembershipCreateStatus.Success:
                        // Add role for new user
                        Roles.AddUserToRole(username, role);
                        GlobalVariables.Logger.Info("newUser.ProviderUserKey: " + newUser.ProviderUserKey);
                        // Update ID
                        var users = new Users
                        {
                            ID = (Guid)newUser.ProviderUserKey,
                            Name = name,
                            Phone = phone,
                            Address = address
                        };
                        DataContext.Instance.Users.AddObject(users);
				        DataContext.Instance.SaveChanges();
                        break;
                    case MembershipCreateStatus.DuplicateUserName:
                        errorText = "The username you have entered is exist, please input another!";
                        break;
                    case MembershipCreateStatus.DuplicateEmail:
                        errorText = "The email you have entered is exist, please input another!";
                        break;
                    case MembershipCreateStatus.InvalidEmail:
                        errorText = "The email you have entered is invalid, please input another.";
                        break;
                    case MembershipCreateStatus.InvalidPassword:
                        errorText = "The password you have entered is invalid, please input another.";
                        break;
                    default:
                        errorText = "Have a unknow problem, your account have not been created.";
                        break;
                }
                if (errorText != "")
                {
                    GlobalVariables.Logger.Error(errorText);
                }
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
            return errorText;
		}

		public bool Delete(Guid id)
		{
			try
			{
				var delitem = DataContext.Instance.Users.FirstOrDefault(item => item.ID == id );
                var username = delitem.aspnet_Users.UserName;
				DataContext.Instance.Users.DeleteObject(delitem);
				DataContext.Instance.SaveChanges();
                Membership.DeleteUser(username, true);
				return true;
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
			return false;
		}

		public bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
			return false;
		}

		public List<Users> RetrieveByID(Guid id)
		{
			try
			{
				return (from item in DataContext.Instance.Users where  item.ID == id  select item).ToList();
			}
			catch(Exception ex)
			{
				if (ex.InnerException != null)
				{
					GlobalVariables.Logger.Error(ex.InnerException.Message);
				}
				else
				{
					GlobalVariables.Logger.Error(ex.Message);
				}
			}
			return new List<Users>();
		}

        public List<Users> RetrieveByUserName(string username)
        {
            try
            {
                return (from item in DataContext.Instance.Users where item.aspnet_Users.UserName == username select item).ToList();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error(ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error(ex.Message);
                }
            }
            return new List<Users>();
        }

        public bool ChangePassword(string userName, string oldpassword, string newpassword)
        {
            try
            {
                MembershipUser currentUser = Membership.Provider.GetUser(userName, true);
                return currentUser.ChangePassword(oldpassword, newpassword);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error(ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error(ex.Message);
                }
            }
            return false;
        }

        public string ResetPassword(string userName, string email)
        {
            var errTxt = string.Empty;
            try
            {
                MembershipUser currentUser = Membership.Provider.GetUser(userName, true);
                if (currentUser.Email.Trim() == email.Trim())
                {
                    var randPassword = currentUser.ResetPassword();
                    if (randPassword != string.Empty)
                    {
                        var _repInformationWeb = new InformationWebRepository();
                        var informationWeb = _repInformationWeb.SelectAll().First();
                        var EmailContact = string.Empty;
                        if (informationWeb != null)
                        {
                            EmailContact = informationWeb.Email;
                            WebConfiguration.EmailLienHe = informationWeb.Email;
                            WebConfiguration.PasswordEmailLienHe = informationWeb.PassEmail;
                        }
                        var emailTmp = File.ReadAllText(HostingEnvironment.ApplicationPhysicalPath + @"\Content\ResetPasswordTemplate.html");
                        emailTmp = emailTmp.Replace("[Password]", randPassword);
                        emailTmp = emailTmp.Replace("[EmailContact]", EmailContact);
                        emailTmp = emailTmp.Replace("[SiteName]", WebConfiguration.SiteName);
                        //GlobalVariables.Logger.Info("emailTmp: " + emailTmp);
                        if (!MailHelper.SendingMail("Reset Password in " + WebConfiguration.SiteName, emailTmp, email))
                        {
                            errTxt = "Cannot sending new password to email " + email;
                        }
                    }
                    else
                    {
                        errTxt = "Cannot generate new password, please try again";
                    }
                }
                else
                {
                    errTxt = "User input invalid email or email is not exist";
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error(ex.InnerException.Message);
                    errTxt = ex.InnerException.Message;
                }
                else
                {
                    GlobalVariables.Logger.Error(ex.Message);
                    errTxt = ex.Message;
                }
            }
            return errTxt;
        }
	}
}